using System;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.LINK.Components;

namespace ASPNETVN.PORTAL.Modules.LINK
{
    public partial class EditLink : AddEditItemPage
    {
        protected override void OnInit(EventArgs e)
        {
            ButtonCancel = this.btnCancel;
            ButtonUpdate = this.btnUpdate;
            ButtonDelete = this.btnDelete;

            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (this.ItemID != 0)
                {
                    Item link = Item.Load(this.ItemID);
                    if (link != null)
                    {
                        txtTitle.Text = link.Title;
                        txtUrl.Text = link.Url;
                        txtDescription.Text = link.Description;
                        txtOrder.Text = link.Order.ToString();
                        cbTarget.SelectedValue = link.Target;
                        lblCreatedBy.Text = link.CreatedBy;
                        lblCreatedDate.Text = link.CreationDate.ToString();
                    }
                }
                else
                {
                    lblCreatedBy.Text = PortalSecurity.CurrentUser.Identity.Email;
                    lblCreatedDate.Text = DateTime.Now.ToString();
                }
            }
        }

        protected override void OnUpdate(EventArgs e)
        {
            base.OnUpdate(e);
            if (Page.IsValid)
            {
                // Create an instance of the Link DB component
                Item link = new Item();

                link.ModuleID = this.ModuleID;
                link.Title = txtTitle.Text;
                link.Url = txtUrl.Text;
                link.Description = txtDescription.Text;

                if (txtOrder.Text.Length == 0)
                    link.Order = 0;
                else
                    link.Order = Convert.ToInt32(txtOrder.Text);

                link.Target = cbTarget.SelectedValue;

                if (this.ItemID == 0)
                {
                    link.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                    link.CreationDate = DateTime.Now;
                    link.Insert();
                }
                else
                {
                    link.ID = this.ItemID;
                    link.CreationDate = DateTime.Parse(lblCreatedDate.Text);
                    link.Update();
                }

                ReturnToReferrerPage();
            }
        }

        protected override void OnDelete(EventArgs e)
        {
            base.OnDelete(e);

            if (this.ItemID != 0)
            {
                Item.Delete(this.ItemID);
            }

            ReturnToReferrerPage();
        }       
    }
}